package top.moonkit.rs_pro.controller;

import cn.hutool.core.util.StrUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.moonkit.rs_pro.common.Result;
import top.moonkit.rs_pro.entity.User;
import top.moonkit.rs_pro.entity.vo.LoginRequestVO;
import top.moonkit.rs_pro.entity.vo.SendCodeRequestVO;
import top.moonkit.rs_pro.exception.BusinessException;
import top.moonkit.rs_pro.patterns.CheckCode.CheckCodeFactory;
import top.moonkit.rs_pro.patterns.login.LoginProcessorFactory;
import top.moonkit.rs_pro.service.UserService;
import top.moonkit.rs_pro.utils.Au;
import top.moonkit.rs_pro.utils.Mu;

/**
 * 登录控制器
 */
@RestController
@RequestMapping("/auth")
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 登录接口
     *
     * @param loginRequest 登录请求参数
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginRequestVO loginRequest, HttpServletRequest request) {

        // 参数校验
        if (StrUtil.isBlank(loginRequest.getAccount()) ||
                (StrUtil.isBlank(loginRequest.getPassword()) && StrUtil.isBlank(loginRequest.getCode()))) {
            throw new BusinessException(Mu.m("login.username_or_password_error"));
        }

        // 查找用户
        User user = userService.findUserByAccount(loginRequest.getAccount());
        if (user == null) {
            throw new BusinessException(Mu.m("login.username_or_password_error"));
        }

        // 检查用户状态
        if (user.getStatus() != null && user.getStatus() == 1) {
            throw new BusinessException(Mu.m("login.user_disabled"));
        }
        LoginProcessorFactory
                .buildProcessor(loginRequest.getAccount(), StrUtil.isNotBlank(loginRequest.getPassword()))
                .verifyAccount(loginRequest, user);

        // 生成token
        return Result.success(Au.createToken(user.getId(), loginRequest.getRememberMe()));
    }

    /**
     * 登出接口
     *
     * @param request HTTP请求
     * @return 登出结果
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpServletRequest request) {
        Au.removeToken();
        return Result.success(Mu.m("login.logout"));
    }

    /**
     * 发送验证码
     */
    @PostMapping("/send-code")
    public Result<String> sendCode(@RequestBody SendCodeRequestVO vo) {
        CheckCodeFactory.buildService( vo.getAccount()).sendCode();
        return Result.success(Mu.m("login.code_send_success"));
    }

}